var token_url = "/oauth/token";
var client_id = "mtg-grid-management";
var client_secret = "1234567890";
var access_token = window.sessionStorage.access_token;
var refresh_token = window.sessionStorage.refresh_token;


$.ajaxSetup({
    beforeSend: function (xhr) {
        if (this.url === token_url) {
            return true;
        }
        xhr.setRequestHeader('Authorization', 'Bearer ' + access_token + '');
    },
    complete: function (xhr) {
        if (xhr.status === 401 && xhr.responseJSON.error === 'invalid_token') {
            // alert('token 已经过期');
            clearToken();
            window.location.href = '/login';
            // refreshToken();
        }
    }
});


function refreshToken() {
    var data = {
        'client_id': client_id,
        'client_secret': client_secret,
        'grant_type': 'refresh_token',
        'refresh_token': refresh_token
    };
    $.ajax({
        url: token_url,
        type: "POST",
        data: data,
        async: false,
        success: function (xhr) {
            saveToken(xhr);
        },
        error: function (event, xhr, options) {
            if (xhr.status === 401 && xhr.responseJSON.error === 'invalid_token') {
                alert('refresh 已经过期');
                window.location.href = '/login';
            }
        }
    });


}


function saveToken(xhr) {
    window.sessionStorage.access_token = xhr.access_token;
    window.sessionStorage.refresh_token = xhr.refresh_token;

}


function clearToken() {
    window.sessionStorage.clear();
}


// $(document).ajaxError(function (event, xhr, options) {
//
//
//     if (xhr.status === 401 && xhr.responseJSON.error === 'invalid_token') {
//         alert('token 已经过期');
//         console.log(options.url);
//         window.location.href = '/login';
//     }
//     console.log(xhr);
//
//     console.log(xhr.status);
//
//     console.log(options);
//
// });